package com.wantong.jianpu.viewmodels;

import android.app.Application;

import androidx.annotation.NonNull;

import com.wantong.jianpu.activitys.MainActivity;
import com.wantong.jianpu.base.BaseResultBean;
import com.wantong.jianpu.beans.LoginBean;
import com.wantong.jianpu.models.LoginModel;
import com.wantong.jianpu.net.BaseObserver;
import com.wantong.jianpu.utils.XUtils;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * @author PACY
 * @date 2022/5/7
 * description:
 */
public class LoginViewModel extends BaseViewModel {
    public LoginModel model;
    public SingleLiveEvent<String> userName=new SingleLiveEvent<>();
    public SingleLiveEvent<String> passWord=new SingleLiveEvent<>();
    public LoginViewModel(@NonNull Application application) {
        super(application);
        model=new LoginModel();
    }

    @Override
    protected void init() {
        super.init();
        if(XUtils.isLogin()){
            startActivity(MainActivity.class);
            finish();
        }
    }

    public BindingCommand login=new BindingCommand(() -> {
        loginRequest();

    });

    /**
     * 登录
     */
    public void loginRequest(){
        if(StringUtils.isEmpty(userName.getValue())){
            ToastUtils.show("请输入用户名");
            return;
        }
        if(StringUtils.isEmpty(passWord.getValue())){
            ToastUtils.show("请输入密码");
            return;
        }
        showDialog();
        Map<String,Object> params=new HashMap<>();
        params.put("username",userName.getValue());
        params.put("password",passWord.getValue());
        model.login(params, new BaseObserver<LoginBean>() {
            @Override
            public void onSuccess(BaseResultBean<LoginBean> t) {
                XUtils.saveLogin(t.getData());
                startActivity(MainActivity.class);
                finish();
            }

            @Override
            public void onComplete() {
                super.onComplete();
                dismissDialog();
            }
        },getLifecycleProvider());
    }
}
